<?php
/* 解析命令
 * 如http://hellohtml5.test.com/index.php/!rwres!ua:haha/http://test.test.com/test.css
 * /!rwres!ua:haha 即为命令
 * 命令以!分割，参数以:分割
 * rwres 为不带参数的命令
 * ua:haha 为命令并携带参数haha传入，多个参数以,分割
 */
class CommandParser {

	// 命令与命令的分隔符
	private static $COMMAND_SEP = "!";
	// 命令与参数的分隔符
	private static $COMMAND_NAME_PARAMS_SEP = ":";
	// 参数与参数的分隔符
	private static $COMMAND_PARAMS_SEP = ",";
	// commands字符串
	private $_command_str;
	// 数组格式的commands
	private $_command_arr;

	public function __construct($str) {
		$this->_command_str = "";
		$this->_command_arr = array();
		$this->parseCommand($str);
	}

	// 分析命令
	private function parseCommand($str) {
		if(preg_match("@(".self::$COMMAND_SEP."[^!]*)*\/$@",$str,$matches)) {
			if (!empty($matches[0])) {
				$matches[0] = preg_replace("@\/$@","",$matches[0]);
				$matches[0] = preg_replace("@".self::$COMMAND_SEP."+@","!",$matches[0]);// 兼容性，去重
				$matches[0] = preg_replace("@".self::$COMMAND_NAME_PARAMS_SEP."+@",":",$matches[0]);// 兼容性，去重
				$matches[0] = preg_replace("@".self::$COMMAND_PARAMS_SEP."+@",",",$matches[0]);// 兼容性，去重

				foreach(explode(self::$COMMAND_SEP,$matches[0]) as $command) {
					if (!empty($command)) {
					    $command_arr = explode(self::$COMMAND_NAME_PARAMS_SEP,$command);
				    	if (count($command_arr) == 1) {
				    		$this->_command_arr[$command_arr[0]] = array();
				    	} else {
				    		$this->_command_arr[$command_arr[0]] = explode(self::$COMMAND_PARAMS_SEP,$command_arr[1]);
				    	}
				    }
				}
			    $this->_commands_str = $matches[0];
			}
		}
	}

	// 是否有命令
	public function has($command_name) {
		return array_key_exists($command_name,$this->_command_arr);
	}

	// 获取url命令中的参数，无参数返回空数组
	// 无命令返回false
	public function getParams($command_name) {
		if ($this->has($command_name)) {
			return $this->_command_arr[$command_name];
		}
		return false;
	}

	// 生成命令符
	public static function genOne($command_name,$params=array()) {
		return self::$COMMAND_SEP.$command_name.implode(self::$COMMAND_NAME_PARAMS_SEP,$params);
	}

	public function get() {
		return $this->_command_arr;
	}
	// 获取url中的命令
	public function toString() {
		return $this->_command_str;
	}
}
